package com.baseframe.sms.template;

import com.apistd.uni.Uni;
import com.apistd.uni.UniException;
import com.apistd.uni.UniResponse;
import com.apistd.uni.sms.UniMessage;
import com.apistd.uni.sms.UniSMS;
import com.baseframe.sms.entity.Sms;
import com.baseframe.sms.entity.SmsSendData;
import com.baseframe.sms.exception.SmsException;
import com.baseframe.tool.result.R;
import com.baseframe.tool.utils.data.EnvUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class UniSmsTemplate extends AbstractSmsTemplate{

    public UniSmsTemplate(Sms sms) {
        super(sms);
    }

    @Override
    public R<Object> send(SmsSendData sendData) {
        Sms sms = super.getSms();
        Uni.init(sms.getAccessKey(),sms.getSecretKey());
        //根据模板内容构建请求参数
        Map<String,String> params = new HashMap<>();
        String[] envStr = EnvUtil.getEnvStr(sms.getTemplateContent());
        //构建请求参数
        for (String env : envStr) {
            params.put(env,sendData.getParams().get(env));
        }
        //构建参数
        UniMessage uniMessage = UniSMS.buildMessage()
                .setTo(sendData.getPhone())
                .setSignature(sms.getSign())
                .setTemplateId(sms.getTemplate())
                .setTemplateData(params);



        try {
            //发送短信
            UniResponse response = uniMessage.send();
            log.info("短信发送，原始请求结果:{}",response);
            return  "0".equals(response.code)?R.success("发送成功~"):R.fail(response.message);
        }catch (UniException e){
            log.error("短信发送异常:{}",e.message);
            throw new SmsException(e);

        }



    }


}
